package bytes

import (
	"bytes"
	"fmt"
	"io"
)

func Buffer() {
	var b bytes.Buffer
	fmt.Printf("b: %v\n", b)

	b2 := new(bytes.Buffer)
	fmt.Printf("b2: %v\n", b2)

	b3 := bytes.NewBuffer([]byte("hello"))
	fmt.Printf("b3: %v\n", b3)

	b4 := bytes.NewBufferString("hello2")
	fmt.Printf("b4: %v\n", b4)

}

func BufferWrite() {
	var buf bytes.Buffer
	buf.Write([]byte("h"))
	fmt.Println(buf.String())
	buf.WriteString("e")
	fmt.Println(buf.String())
	buf.WriteByte('l')
	fmt.Println(buf.String())
	buf.WriteRune('世')
	fmt.Println(buf.String())

}

func BufferRead() {
	s := bytes.NewBufferString("123456789")
	c := make([]byte, 2)

	for {
		n, err := s.Read(c)
		if err == io.EOF {
			break
		}
		fmt.Printf("n: %v\n", n)
		fmt.Printf("c[0:n]: %v\n", string(c[0:n]))
	}

}

func Reader() {
	// 通过[]byte创建Reader
	data := "123456789"
	reader := bytes.NewReader([]byte(data))
	//返回未读取部分的长度
	fmt.Printf("reader.Len(): %v\n", reader.Len())
	//返回底层数组总长度
	fmt.Printf("reader.Size(): %v\n", reader.Size())
	fmt.Println("------------")

	buf := make([]byte, 2)
	for {
		n, err := reader.Read(buf)
		if err != nil {
			break
		}
		fmt.Println(string(buf[:n]))
	}
	fmt.Println("--------------")

	// 设置偏移量  因为上面的操作已经修改了读取位置等信息
	reader.Seek(0, 0)
	for {
		// 按一个字节读取
		b, err := reader.ReadByte()
		if err != nil {
			break
		}
		fmt.Println(string(b))
	}
	fmt.Println("-------------")
	reader.Seek(0, 0)
	off := int64(0)
	for {
		n, err := reader.ReadAt(buf, off)
		if err != nil {
			break
		}
		off += int64(n)
		fmt.Println(off, string(buf[:n]))
	}
}
